import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  Form,
  Input,
  Button,
  Card,
  Table,
  Tooltip,
  Popconfirm,
  message,
  Modal,
} from "antd";
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
// 引入类型一般会加上type
import type { TableColumnsType } from "antd";
import type {
  HospitalSetItem,
  HospitalSetList,
  FormValues,
} from "@/api/hospital/hospitalSet/types";
import {
  reqGetHospitalSetList,
  reqRemoveHospitalSet,
  reqBatchRemoveHospitalSet,
} from "@/api/hospital/hospitalSet";

import "./index.less";

// table数据
// const hospitalSetList = [
//   {
//     id: 8,
//     createTime: "2022-01-18 10:53:10",
//     updateTime: "2023-06-04 18:05:56",
//     isDeleted: 0,
//     param: {},
//     hosname: "北京市海淀区同步中医骨科医院",
//     hoscode: "1000_7",
//     apiUrl: "http://localhost:8220",
//     signKey: "6f8006485dca34cd5849b724981dbe99",
//     contactsName: "王伟",
//     contactsPhone: "13134564567",
//     status: 1,
//   },
// ];

export default function HospitalSet() {
  const [hospitalSetList, setHospitalSetList] = useState<HospitalSetList>([]); // 医院设置列表数据
  const [total, setTotal] = useState(0); // 总数
  const [page, setPage] = useState(1); // 当前页码
  const [limit, setLimit] = useState(5); // 每页条数
  const [loading, setLoading] = useState(false); // loading
  const [hosname, setHosname] = useState("");
  const [hoscode, setHoscode] = useState("");

  // table列
  const columns: TableColumnsType<HospitalSetItem> = [
    {
      title: "序号", // 列的标题
      key: "index",
      // 定义函数的参数时，如果声明参数但是又不需要使用，加上_
      render: (_, _record, index) => {
        // render方法返回值就是渲染的内容
        // record 就是遍历某行数据
        // index 就是遍历某行下标
        return <div className="index">{index + 1}</div>;
      },
      width: 100, // 列的宽度
      align: "center", // 居中对齐
    },
    {
      title: "医院名称",
      // 如果只写dataIndex，dataIndex的内容就是最终渲染的内容
      // 如果写了render，render方法返回值就是渲染的内容
      dataIndex: "hosname",
      key: "hosname",
      width: 200,
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
      key: "hoscode",
      width: 200,
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
      key: "apiUrl",
      width: 200,
    },
    {
      title: "签名",
      dataIndex: "signKey",
      key: "signKey",
      width: 200,
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
      key: "contactsName",
      width: 200,
    },
    {
      title: "联系人手机",
      dataIndex: "contactsPhone",
      key: "contactsPhone",
      width: 200,
    },
    {
      title: "操作",
      key: "operator",
      width: 150,
      fixed: "right", // 固定的位置
      render: (_, record) => {
        return (
          <>
            <Tooltip placement="top" title="修改医院">
              <Link to={`/syt/hospital/hospitalset/edit/${record.id}`}>
                <Button type="primary" icon={<EditOutlined />} />
              </Link>
            </Tooltip>

            <Popconfirm
              title={`确定删除 ${record.hosname} 吗?`}
              onConfirm={confirmDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Tooltip placement="top" title="删除医院">
                <Button type="primary" danger icon={<DeleteOutlined />} />
              </Tooltip>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  // 删除
  // 使用高阶函数传递id参数
  const confirmDelete = (id: number) => {
    return async () => {
      await reqRemoveHospitalSet(id);
      message.success("删除医院设置成功");
      getHospitalSetList(); // 获取新数据展示
    };
  };

  const [form] = Form.useForm();

  const getHospitalSetList = async () => {
    setLoading(true);
    const res = await reqGetHospitalSetList({
      page,
      limit,
      hosname,
      hoscode,
    });
    setHospitalSetList(res.records);
    setTotal(res.total);
    setLoading(false);
  };

  useEffect(() => {
    // useEffect不允许定义成异步函数，所以才需要内部定义一个新函数去处理
    getHospitalSetList();
  }, [page, limit, hosname, hoscode]);

  // 当页码或 pageSize 改变触发的回调
  const handlePaginationChange = (page: number, limit: number) => {
    setPage(page);
    setLimit(limit);
  };

  // 处理表单提交事件
  const onFinish = (values: FormValues) => {
    setHosname(values.hosname as string);
    setHoscode(values.hoscode || "");
    setPage(1);
  };

  // 重置表单
  const onReset = () => {
    // 只会将Form表单项内容清空，并不会更新数据
    form.resetFields();
    // 手动清空数据，触发useEffect，重新获取数据展示
    setHosname("");
    setHoscode("");
    setPage(1);
  };

  const [idList, setIdList] = useState<number[]>([]);

  // 复选框change
  const handleRowSelectionChange = (selectedRowKeys: React.Key[]) => {
    // selectedRowKeys 获取选中行key属性的值（因为我们行设置key属性值是id，所以最终得到的是id）
    setIdList(selectedRowKeys as number[]);
  };

  // 批量删除按钮
  const batchRemove = () => {
    Modal.confirm({
      title: "您确认要批量删除数据吗?",
      // content: "",
      // okText: "确定",
      // cancelText: "取消",
      // onCancel() {},
      async onOk() {
        await reqBatchRemoveHospitalSet(idList);
        message.success("批量删除成功");
        getHospitalSetList();
        setIdList([]);
      },
    });
  };

  return (
    <Card>
      {/* 
        layout="inline" 让表单项元素以行内元素方式排列
      */}
      <Form layout="inline" onFinish={onFinish} form={form}>
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>
        <Form.Item>
          {/* htmlType="submit" 设置按钮为提交表单按钮 */}
          <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
            查询
          </Button>
          <Button onClick={onReset}>清空</Button>
        </Form.Item>
      </Form>

      <div className="my-20">
        <Link to="/syt/hospital/hospitalset/add">
          <Button type="primary">添加</Button>
        </Link>
        <Button
          type="primary"
          danger
          disabled={!idList.length}
          onClick={batchRemove}
        >
          批量删除
        </Button>
      </div>

      {/* 
        columns 列数据
        dataSource 行数据
        bordered 带边框
        scroll 指定x（y）轴大小
        rowKey="id" 设置每行元素的key属性取值
      */}
      <Table
        columns={columns}
        dataSource={hospitalSetList}
        bordered
        scroll={{ x: 1450 }}
        rowKey="id"
        pagination={{
          total,
          showTotal: (total) => `总共 ${total} 条`,
          showSizeChanger: true, // 显示每页条数下拉列表
          pageSizeOptions: [5, 10, 15, 20],
          showQuickJumper: true, // 显示快速跳转
          onChange: handlePaginationChange,
          current: page,
          pageSize: limit,
        }}
        loading={loading}
        rowSelection={{
          type: "checkbox",
          onChange: handleRowSelectionChange,
        }}
      />
    </Card>
  );
}
